import json

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QImage
from PyQt5 import uic
from PyQt5.QtWidgets import QMessageBox

from qtThread import QtThread


# Qt 显示个人信息页面实现代码
class Personal():

    def __init__(self, mainWindow):
        self.mainWindow = mainWindow
        self.ui = mainWindow.ui.personal
        self.session = mainWindow.session
        self.ui.btn_submitInfo.setHidden(True)

        self.ui.edit_username.textChanged.connect(self.infoChange)
        self.ui.edit_realname.textChanged.connect(self.infoChange)
        self.ui.btn_editPwd.clicked.connect(self.editPwd)
        self.ui.btn_editInfo.clicked.connect(self.editInfo)
        self.ui.btn_submitInfo.clicked.connect(self.submitInfo)

        # 配置密码修改页面
        self.passwordDetails = uic.loadUi('ui/passwordEdit.ui')
        self.passwordDetails.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint)
        self.passwordDetails.edit_oldPwd.textChanged.connect(self.oldPasswordChange)
        self.passwordDetails.edit_newPwd.textChanged.connect(self.newPasswordChange)
        self.passwordDetails.edit_confirmPwd.textChanged.connect(self.confirmPasswordChange)
        self.passwordDetails.btn_submit.clicked.connect(self.editPwdSubmit)
        self.passwordDetails.btn_cancel.clicked.connect(self.editPwdCancel)

        # 配置输入项错误时的显示样式
        self.commonStyle = 'border-radius: 5px;/*设置圆角的大小*/ \n' \
                           'padding: 0 8px;/*如果没有内容光标在开始往后移动0.8像素点*/\n' \
                           'selection-background-color:rgb(33,33,33);\n'
        if self.mainWindow.isWhite:
            self.styleReadOnly = 'border: 1px solid rgb(210,210,210);/*设置边框的粗细，以及颜色*/ \n'
        else:
            self.styleReadOnly = 'border: 1px solid white;/*设置边框的粗细，以及颜色*/ \n' + self.commonStyle
        self.styleEditable = 'border: 1px solid green;/*设置边框的粗细，以及颜色*/ \n' + self.commonStyle
        self.styleERROR = 'border: 1px solid red;/*设置边框的粗细，以及颜色*/ \n' + self.commonStyle

    # 调用子线程加载进入页面时必要的数据
    def loadData(self):
        self.infoThread = QtThread(url=self.mainWindow.url + '/admin/user/userInfo', cookies=self.session.cookies)
        self.infoThread.load_data.connect(self.loadInfo)
        self.infoThread.start()

    # 子线程从后端获取个人信息后执行显示操作
    def loadInfo(self, text):
        data = text['data']
        self.ui.edit_username.setText(data['username'])
        self.ui.edit_realname.setText(data['realname'])
        self.ui.edit_remark.setPlainText(data['remark'])
        self.ui.label_username.setText(data['username'])

        # 设置文本框不可编辑
        self.setLineEditReadOnly(True)

        # 设置隐藏提交编辑的按钮
        self.ui.btn_submitInfo.setHidden(True)

        # 加载头像图片
        url = self.mainWindow.url + data['avatar']
        img = QImage.fromData(self.session.get(url).content)
        pixmap = QPixmap.fromImage(img)
        self.ui.avatar.setPixmap(pixmap)
        self.ui.avatar.setScaledContents(True)

        # 加载登录记录
        self.ui.list_loginLog.clear()
        user_logs = data['user_logs']
        for log in user_logs:
            self.ui.list_loginLog.addItem(log['ip'] + '\t' + log['create_time'])

    # 以下为个人信息页面代码
    # 点击个人信息编辑按钮后的事件
    def editInfo(self):
        # 使文本输入栏可以编辑
        self.setLineEditReadOnly(False)
        # 显示提交按钮
        self.ui.btn_submitInfo.setHidden(False)

    # 提交个人信息修改的事件
    def submitInfo(self):
        data = {
            'username': self.ui.edit_username.text(),
            'realName': self.ui.edit_realname.text(),
            'details': self.ui.edit_remark.toPlainText()
        }
        headers = {
            'content-type': 'application/json'
        }
        self.session.put(self.mainWindow.url + '/admin/user/updateInfo', json=data, headers=headers)
        self.loadData()

    # 个人信息修改时触发事件，判断输入的个人信息是否合法
    def infoChange(self):
        if self.ui.edit_username.text() == '':
            self.ui.edit_username.setStyleSheet(self.styleERROR)
            self.ui.label_usernameERROR.setText(u'账号不能为空')
        else:
            self.ui.edit_username.setStyleSheet(self.styleEditable)
            self.ui.label_usernameERROR.setText('')

        if self.ui.edit_realname.text() == '':
            self.ui.edit_realname.setStyleSheet(self.styleERROR)
            self.ui.label_realnameERROR.setText(u'姓名不能为空')
        else:
            self.ui.edit_realname.setStyleSheet(self.styleEditable)
            self.ui.label_realnameERROR.setText('')

    # 设置文本输入栏是否可读与是否有清除数据按钮
    def setLineEditReadOnly(self, enable):
        self.ui.edit_username.setStyleSheet(self.styleReadOnly if enable else self.styleEditable)
        self.ui.edit_username.setReadOnly(enable)
        self.ui.edit_username.setClearButtonEnabled(not enable)
        self.ui.edit_realname.setStyleSheet(self.styleReadOnly if enable else self.styleEditable)
        self.ui.edit_realname.setReadOnly(enable)
        self.ui.edit_realname.setClearButtonEnabled(not enable)
        self.ui.edit_remark.setStyleSheet(self.styleReadOnly if enable else self.styleEditable)
        self.ui.edit_remark.setReadOnly(enable)

    # 以下为修改密码窗口代码
    # 点击编辑密码按钮触发事件，清空密码编辑窗口内的数据，显示窗口
    def editPwd(self):
        self.passwordDetails.edit_oldPwd.setText('')
        self.passwordDetails.edit_oldPwd.setStyleSheet(self.styleReadOnly)
        self.passwordDetails.label_oldPwdERROR.setText('')

        self.passwordDetails.edit_newPwd.setText('')
        self.passwordDetails.edit_newPwd.setStyleSheet(self.styleReadOnly)
        self.passwordDetails.label_newPwdERROR.setText(u'')

        self.passwordDetails.edit_confirmPwd.setText('')
        self.passwordDetails.edit_confirmPwd.setStyleSheet(self.styleReadOnly)
        self.passwordDetails.label_confirmPwdERROR.setText(u'')

        if self.mainWindow.isWhite:
            self.passwordDetails.setStyleSheet('QDialog{background-color: rgb(255, 255, 255)}')
            self.passwordDetails.label.setStyleSheet(u'color: black;')
            self.passwordDetails.label_2.setStyleSheet(u'color: black;')
            self.passwordDetails.label_3.setStyleSheet(u'color: black;')
            self.passwordDetails.frame.setStyleSheet("QLineEdit {\n"
                                                     "    background-color: rgb(255, 255, 255);\n"
                                                     "    color: rgb(0, 0, 0);\n"
                                                     "    border-radius: 5px;\n"
                                                     "    border: 2px solid rgb(210,210,210);\n"
                                                     "    padding-left: 10px;\n"
                                                     "}\n"
                                                     "QLineEdit:hover {\n"
                                                     "    border: 2px solid rgb(85, 170, 255);\n"
                                                     "}\n"
                                                     "QLineEdit:focus {\n"
                                                     "    border: 2px solid rgb(91, 101, 124);\n"
                                                     "}\n"
                                                     "QPushButton {\n"
                                                     "	border: 2px solid rgb(210, 210, 210);\n"
                                                     "	border-radius: 5px;\n"
                                                     "	color:rgb(0,0,0);\n"
                                                     "	background-color: rgb(210, 210, 210);\n"
                                                     "}\n"
                                                     "QPushButton:hover {\n"
                                                     "	background-color: rgb(190,190,190);\n"
                                                     "	border: 2px solid rgb(180,180,180);\n"
                                                     "}\n"
                                                     "QPushButton:pressed {\n"
                                                     "	background-color: rgb(200,200,200);\n"
                                                     "	border: 2px solid rgb(190,190,190);\n"
                                                     "}")
        self.passwordDetails.exec_()

    # 提交新密码按钮触发事件
    def editPwdSubmit(self):

        # 获取旧密码，新密码，确认密码进行合法性判断
        oldPwd = self.passwordDetails.edit_oldPwd.text()
        newPwd = self.passwordDetails.edit_newPwd.text()
        confirmPwd = self.passwordDetails.edit_confirmPwd.text()

        if oldPwd == '':
            ERROR(u'请输入原密码')

            return
        if newPwd == '':
            ERROR(u'请输入新密码')
            return

        if confirmPwd == '':
            ERROR(u'请确认新密码')
            return

        if newPwd != confirmPwd:
            ERROR(u'新密码与确认新密码不相同')
            return

        # 传输密码修改至后端
        data = {
            'oldPassword': oldPwd,
            'newPassword': newPwd,
            'confirmPassword': confirmPwd
        }
        headers = {
            'content-type': 'application/json'
        }
        response = self.session.put(self.mainWindow.url + '/admin/user/editPassword', json=data, headers=headers)

        res = json.loads(response.text)

        success = res['success']

        # 成功则弹窗提示并退出窗口
        if (success):
            msg_box = QMessageBox(QMessageBox.Information, '修改成功', '密码修改成功')
            msg_box.exec_()
            self.passwordDetails.close()
        # 失败则提示返回信息，不退出窗口
        else:
            ERROR(res['msg'])

    # 取消密码编辑触发事件
    def editPwdCancel(self):
        self.passwordDetails.close()

    # 当密码输入框发生变化时，判断输入是否合法
    def oldPasswordChange(self):
        if self.passwordDetails.edit_oldPwd.text() == '':
            self.passwordDetails.edit_oldPwd.setStyleSheet(self.styleERROR)
            self.passwordDetails.label_oldPwdERROR.setText(u'请输入原密码')
        else:
            self.passwordDetails.edit_oldPwd.setStyleSheet(self.styleEditable)
            self.passwordDetails.label_oldPwdERROR.setText('')

    def newPasswordChange(self):
        if self.passwordDetails.edit_newPwd.text() == '':
            self.passwordDetails.edit_newPwd.setStyleSheet(self.styleERROR)
            self.passwordDetails.label_newPwdERROR.setText(u'请输入新密码')
        else:
            self.passwordDetails.edit_newPwd.setStyleSheet(self.styleEditable)
            self.passwordDetails.label_newPwdERROR.setText(u'')

    def confirmPasswordChange(self):
        if self.passwordDetails.edit_confirmPwd.text() == '':
            self.passwordDetails.edit_confirmPwd.setStyleSheet(self.styleERROR)
            self.passwordDetails.label_confirmPwdERROR.setText(u'请确认密码')
        else:
            if self.passwordDetails.edit_newPwd.text() != self.passwordDetails.edit_confirmPwd.text():
                self.passwordDetails.edit_confirmPwd.setStyleSheet(self.styleERROR)
                self.passwordDetails.label_confirmPwdERROR.setText(u'密码不一致')
            else:
                self.passwordDetails.edit_confirmPwd.setStyleSheet(self.styleEditable)
                self.passwordDetails.label_confirmPwdERROR.setText(u'')

    # 修改个人资料按钮触发事件


def ERROR(message):
    msg_box = QMessageBox(QMessageBox.Critical, '错误', message)
    msg_box.exec_()
